<script setup>
import { ref } from "vue";
const passwordData = ref({
  old_pwd: "",
  new_pwd: "",
  re_pwd: "",
});

import { useTokenStore } from "@/stores/token";
const tokenStore = useTokenStore();
import { userInfoService } from "@/api/user";
const userInfoStore = useUserInfoStore();
// 密码校验函数
const checkRePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次确认密码"));
  } else if (value !== passwordData.value.new_pwd) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};
//定义表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 5 到 16 个字符", trigger: "blur" },
  ],
  new_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 5 到 16 个字符", trigger: "blur" },
  ],
  re_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 5 到 16 个字符", trigger: "blur" },
    { validator: checkRePassword, trigger: "blur" },
  ],
};

//修改密码
import { ElMessage } from "element-plus";
import { userPasswordUpdateService } from "@/api/user";
import router from "@/router";

const updatePassword = async () => {
  let result = await userPasswordUpdateService(passwordData.value);
  ElMessage.success(result.message ? result.message : "修改成功");
  //清空token
  tokenStore.removeToken();
  userInfoStore.removeInfo();
  //跳转到登录页面
  router.push("/login");
  ElMessage.success("请重新登录");
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form
          :model="passwordData"
          :rules="rules"
          label-width="100px"
          size="large"
        >
          <el-form-item label="旧密码" prop="old_pwd">
            <el-input type="password" v-model="passwordData.old_pwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input type="password" v-model="passwordData.new_pwd"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="re_pwd">
            <el-input type="password" v-model="passwordData.re_pwd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword"
              >提交修改</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
